package com.recipedb.sprint.service.impl;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import com.recipedb.sprint.entity.BudgetCount;
import com.recipedb.sprint.entity.Sessions;
import com.recipedb.sprint.entity.UseCount;
import com.recipedb.sprint.repository.*;
import com.recipedb.sprint.service.StatsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatsServiceImpl implements StatsService {

    private final SessionsRepository sessionsRepo;
    private final BrandCountRepository brandRepo;
    private final KeywordCountRepository keywordRepo;
    private final UseCountRepository useRepo;
    private final BudgetCountRepository budgetRepo;

    // 购车需求关键词词典
    private final Set<String> carDemandKeywords = Set.of(
            // 使用场景类
            "家庭", "家用", "代步", "通勤", "上班", "商务", "商用", "旅行", "旅游", "自驾",
            "越野", "长途", "城市", "市区", "郊区",

            // 动力类型类
            "混动", "油电", "电动", "纯电", "新能源", "燃油", "汽油", "柴油", "插电",
            "增程", "氢能源",

            // 车辆类型类
            "SUV", "轿车", "跑车", "MPV", "皮卡", "越野车", "面包车", "货车",

            // 性能需求类
            "省油", "油耗", "动力", "加速", "续航", "充电", "电池",

            // 配置需求类
            "空间", "座位", "七座", "五座", "自动", "手动", "四驱", "两驱", "天窗",
            "导航", "倒车", "雷达", "影像", "空调", "真皮", "座椅",

            // 预算价格类
            "便宜", "实惠", "性价比", "豪华", "高端", "顶配", "低配", "中配",

            // 品牌偏好类
            "国产", "进口", "合资", "德系", "日系", "美系", "欧系",

            // 安全环保类
            "安全", "气囊", "环保", "排放", "节能"
    );

    private final List<String> brandDict = List.of("丰田", "比亚迪", "特斯拉", "本田", "宝马", "奔驰", "奥迪", "大众");

    // 停用词更新为更通用的词汇
    private final Set<String> stopwords = Set.of("的", "了", "和", "是", "我", "也", "在", "有", "就",
            "推荐", "预算", "建议", "场景", "用户", "提供", "使用", "优先", "偏好", "专业",
            "车型", "包含", "核心", "分析", "对比", "购买", "想要", "需要", "需求", "什么");

    public StatsServiceImpl(
            UseCountRepository useCountRepository,
            BudgetCountRepository budgetCountRepository,
            SessionsRepository sessionsRepository,
            BrandCountRepository brandCountRepository,
            KeywordCountRepository keywordCountRepository
    ) {
        this.useRepo = useCountRepository;
        this.budgetRepo = budgetCountRepository;
        this.sessionsRepo = sessionsRepository;
        this.brandRepo = brandCountRepository;
        this.keywordRepo = keywordCountRepository;
    }

    @Override
    @Transactional
    public void processAllSessions() {
        List<Sessions> sessionsList = sessionsRepo.findAllWithAnswerOrPrompt();
        for (Sessions s : sessionsList) {
            processAnswer(s.getAnswer());
            processPrompt(s.getPrompt());
        }
    }

    private void processAnswer(String answer) {
        if (answer == null || answer.isBlank()) return;
        for (String brand : brandDict) {
            if (answer.contains(brand)) {
                brandRepo.upsertBrand(brand);
            }
        }
    }

    private void processPrompt(String prompt) {
        if (prompt == null || prompt.isBlank()) return;

        String userText = extractUserPrompt(prompt);
        if (userText.isBlank()) return;
        extractCarDemandBySegmentation(userText);
    }

    /**
     * 分词匹配方法（保留原逻辑但优化过滤条件）
     */
    private void extractCarDemandBySegmentation(String userText) {
        List<Term> termList = HanLP.segment(userText);
        for (Term term : termList) {
            String word = term.word.trim();

            // 过滤条件
            if (word.length() <= 1) continue;
            if (stopwords.contains(word)) continue;

            // 只保留在购车需求词典中的词汇
            if (carDemandKeywords.contains(word)) {
                keywordRepo.upsertKeyword(word);
            }
        }
    }

    private String extractUserPrompt(String prompt) {
        if (!prompt.contains("用户提示：")) return prompt;
        int idx = prompt.indexOf("用户提示：");
        return prompt.substring(idx + "用户提示：".length()).trim();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getTopKeywords(int limit) {
        return keywordRepo.findTopKeywords(limit)
                .stream()
                .map(k -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("name", k.getKeyword());
                    m.put("value", k.getTotalCount());
                    return m;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getTopBrands(int limit) {
        return brandRepo.findTopBrands(limit)
                .stream()
                .map(b -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("name", b.getBrand());
                    m.put("value", b.getTotalCount());
                    return m;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<UseCount> getMonthlyCounts() {
        return useRepo.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public List<BudgetCount> getBudgetCounts() {
        return budgetRepo.findAll();
    }
}